<template>
  <div class="dialog">
    <el-dialog :title="'基地' + titleText" :visible.sync="showDialog" width="40%" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="120px" class="demo-ruleForm">
        <el-form-item label="基地名称 :" prop="homeBaseName">
          <el-input v-model="formData.homeBaseName" placeholder="请输入基地名称" clearable />
        </el-form-item>
        <el-form-item label="基地标识 :" prop="code">
          <el-input v-model="formData.code" placeholder="请输入基地标识" clearable />
        </el-form-item>
        <el-form-item label="nc组织标识:" prop="ncOrg">
          <div style="display: flex;">
            <el-input v-model="formData.ncOrg" placeholder="请输入组织标识" clearable />
            <el-button class="cancelbtn" @click="chooseNcOrg()">查询组织</el-button>
          </div>
        </el-form-item>
        <el-form-item label="养殖类型 :" prop="breedTypeNo">
          <el-select class="w100p" filterable clearable v-model="formData.breedTypeNo" placeholder="选择养殖类型">
            <el-option v-for="item of breedTypeList" :key="item.breedTypeNo + 'breed'" :label="item.breedTypeName"
              :value="item.breedTypeNo" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人 :" class="w100p" prop="principal">
          <el-input v-model="formData.principal" placeholder="请输入负责人名称" clearable />
        </el-form-item>
        <el-form-item label="联系电话 :" class="w100p" prop="tel">
          <el-input v-model="formData.tel" placeholder="请输入负责人联系电话" clearable />
        </el-form-item>
        <el-form-item label="地址 :" class="w100p" prop="address">
          <el-input v-model="formData.address" placeholder="请输入基地地址" clearable />
        </el-form-item>
        <el-form-item label="说明 :" class="w100p" prop="memo">
          <el-input v-model="formData.memo" type="textarea" placeholder="请输入基地说明" clearable />
        </el-form-item>
        <el-form-item label="基地图片 :" class="w100p">
          <UpLoadImage v-if="show" @getFileIdList="getFileIdList" :limit="1" :idList="fileIdList">
          </UpLoadImage>
          <!-- <UploadImage ref="UploadImage" @child-event="getimageurl" />
          <span v-if="baseImg" class="baseImg">
            <img :src="baseImg" height="40px" alt="">
            <i class="el-icon-close" @click="removeImg"></i>
          </span> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
      <el-dialog width="60%" title="选择组织" :visible.sync="innerVisible" append-to-body>
        <div class="searchList">
          <div class="searchItem"><span class="label">查询名称</span><el-input @change="handleSearch" v-model="name"
              placeholder="请输入内容"></el-input>
          </div>
          <div class="searchItem"><span class="label">组织主键</span><el-input @change="handleSearch" v-model="pk_org"
              placeholder="请输入内容"></el-input></div>
          <div class="searchItem"><span class="label">查询编号</span><el-input @change="handleSearch" v-model="code"
              placeholder="请输入内容"></el-input></div>
        </div>
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column prop="name" label="名称">
          </el-table-column>
          <el-table-column prop="pk_org" label="组织主键">
          </el-table-column>
          <el-table-column prop="code" label="编号">
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button v-if="scope.row.pk_org !== formData.ncOrg" type="text" size="mini"
                @click="queryNcOrg(scope.row)">
                确 定
              </el-button>
              <span v-else>当前已选择</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 15px;text-align: right;" background layout="prev, pager, next" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-size="size">
        </el-pagination>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import homeBaseApi from "@/api/basic-info-manage/homeBase";
import BreedingTypeApi from "@/api/basic-info-manage/breeding-type-manage";
import UpLoadImage from "@/components-production-management/UpLoadImage";
import ncBasicinfoApi from "@/api/nc-basic-info/index";

export default {
  name: '',
  components: { UpLoadImage },
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {
      total: 10,
      page: 1,
      size: 10,
      innerVisible: false,
      formData: {},
      rules: {
        homeBaseName: [
          {
            required: true,
            message: "请输入基地名称",
            trigger: "blur"
          }
        ],
        breedTypeNo: [
          {
            required: true,
            message: "请选择基地类型",
            trigger: "blur"
          }
        ],
        code: [
          {
            required: true,
            message: "请输入基地标识",
            trigger: "blur"
          }
        ],
      },
      fileIdList: [],
      // 基地类型
      HomeBaseTypeList: [],
      breedTypeList: [],
      showDialog: this.show,
      baseImg: '',
      tableData: [],
      name: '',
      pk_org: '',
      code: ''
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;

      this.baseImg = ''
    },
    nowChanceStau(v) {
      if (v === 'add') {
        this.formData = {
          staffName: sessionStorage.getItem('staffName'),
        }
      }
      if (v === 'edit') {
        this.formData = this.editObject
        if (this.formData.logoId) {
          this.fileIdList = [this.formData.logoId]
        } else {
          this.fileIdList = []
        }
      }
    },
  },
  created() {
    this.queryEnum()
  },
  mounted() {
    this.queryOrgOrgsPage();
  },
  methods: {
    chooseNcOrg() {
      this.page = 1;
      this.size = 10;
      this.name = '';
      this.pk_org = '';
      this.code = '';
      this.innerVisible = true;
      this.queryOrgOrgsPage();
    },
    queryNcOrg(row) {
      this.formData.ncOrg = row.pk_org
      this.innerVisible = false;
    },
    handleSearch() {
      this.page = 1;
      this.queryOrgOrgsPage();
    },
    // 查询业务员
    queryOrgOrgsPage() {
      ncBasicinfoApi.queryOrgOrgsPage({
        page: this.page,
        size: this.size,
        entity: {
          name: this.name,
          pk_org: this.pk_org,
          code: this.code
        }
      }).then((res) => {
        let { data } = res;
        this.tableData = data.content || [];
        this.total = data.totalElements || 10
      });
    },
    handleSizeChange(val) {
      this.size = val;
      this.queryOrgOrgsPage();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.queryOrgOrgsPage();
    },
    queryEnum() {
      BreedingTypeApi.queryByCondition().then(res => {
        this.breedTypeList = res.data
      })
    },
    removeImg() {
      this.baseImg = ''
      this.formData.logoId = null
    },
    getFileIdList(idList) {
      if (idList.length > 0) {
        this.formData.logoId = idList[0]
      } else {
        this.formData.logoId = ''
      }
    },
    // 获取当前用户可查看基地列表
    getHomeBase() {
      // 获取顶级组织结构id
      homeBaseApi.queryByUserId().then(res => {
        if (res.length == 0 || res.data == []) {
          this.$message.warning("该账户下无基地权限，请联系管理员！")
          removeToken("token")
          this.$router.push({ path: "/login" })
        } else {
          //默认第一个基地
          // setToken("companyMark", res.data[0].code);
          // setToken("homeBaseId", res.data[0].homeBaseId);
          // setToken("homeBaseType", res.data[0].homeBaseType);
          // setToken("homeBaseName", res.data[0].homeBaseName);
          sessionStorage.setItem("homeBaseList", JSON.stringify(res.data));
        }
      })
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let params = { ...this.formData };
            homeBaseApi.edit(params).then(res => {
              this.getHomeBase()
              if (res.success) {
                this.$message.success("修改成功！");
                this.baseImg = ''
                this.close()
              } else {
                this.$message.error("系统错误,修改失败");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let params = { ...this.formData };
            homeBaseApi.add(params).then(res => {
              this.getHomeBase()
              if (res.success) {
                this.$message.success("添加成功");
                this.baseImg = ''
                this.close()
              } else {
                this.$message.error("系统错误,添加失败");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
      this.address = []
    },
    cancel() {
      this.$emit("cancelDialog");
      this.address = []
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table th {
  color: #000;
  background-color: rgba(120, 182, 193, 0.4) !important;
}

::v-deep .el-table .el-table__row--striped {
  color: #000;
  background-color: rgba(186, 186, 186, 0.4) !important;
}

::v-deep.el-table td,
.el-table th.is-leaf,
.el-table--border,
.el-table--group,
.el-table th.is-leaf {
  border-color: #D3D3D3 !important;
}

::v-deep .el-table th.is-leaf {
  border-color: #D3D3D3 !important;
}

::v-deep .el-table__empty-text {
  color: #000;
}

::v-deep .el-table {
  color: #000;
}

.addInfo {
  width: 100%;
  margin: 10px;
  background-color: #237FC3;
  color: #fff;
  font-size: 18px;

}

.el-form {
  margin-top: 10px;
}

.baseImg {
  position: relative;
  height: 40px;

  i {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
  }
}

.searchList {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;

  .searchItem {
    width: calc(100% - 20px);
    display: flex;
    justify-content: flex-start;

    .label {
      display: inline-block;
      width: 120px;
      padding-right: 15px;
      text-align: right;
      line-height: 30px;
    }
  }
}
</style>
